﻿namespace DesignModeConsole.结构型.享元模式;

/*
 这里的文本编辑器设定只实现文字编辑功能，不包含图片、表格等复杂的编辑功能，我们只是在内存中表示一个文本文件，
只需要记录文字和格式两个部分的信息，格式又包含文字的字体、大小、颜色等信息。
 */

#region 使用享元模式之前

/// <summary>
/// 创建用来保存每个文字具体信息的类
/// </summary>
public class Character1
{
    public Character1(char c, string font, int size, int colorRgb)
    {
        C = c;
        Font = font;
        Size = size;
        ColorRgb = colorRgb;
    }

    public char C { get; set; }

    public string Font { get; set; }

    public int Size { get; set; }

    public int ColorRgb { get; set; }
}

/// <summary>
/// 创建文本编辑器  缺点：里面保存了大量的Character1对象
/// </summary>
public class Editor1
{
    private readonly List<Character1> list = new List<Character1>();

    public void AddCharacter(char c, string font, int size, int colorRgb)
    {
        var character = new Character1(c, font, size, colorRgb);
        list.Add(character);
    }
}

#endregion

#region 使用享元模式

public class CharacterStyle
{
    public CharacterStyle(string font, int size, int colorRgb)
    {
        Font = font;
        Size = size;
        ColorRgb = colorRgb;
    }

    public string Font { get; set; }

    public int Size { get; set; }

    public int ColorRgb { get; set; }

    public override bool Equals(object? obj)
    {
        var style = (CharacterStyle)obj;
        return Font == style.Font && Size == style.Size && ColorRgb == style.ColorRgb;
    }
}

/// <summary>
/// 字体样式工厂
/// </summary>
public class CharacterStypeFactory
{
    private static readonly List<CharacterStyle> list = new List<CharacterStyle>();

    public static CharacterStyle GetStyle(string font, int size, int colorRgb)
    {
        var newStyle = new CharacterStyle(font, size, colorRgb);
        var style = list.FirstOrDefault(t => t.Equals(newStyle));
        if (style != null)
        {
            return style;
        }

        list.Add(newStyle);
        return newStyle;
    }
}

/// <summary>
/// 文字 包含文字样式(样式共享)
/// </summary>
public class Character2
{
    public Character2(char c, CharacterStyle style)
    {
        C = c;
        Style = style;
    }

    public char C { get; set; }
    public CharacterStyle Style { get; set; }
}

/// <summary>
/// 编辑器 获取样式是根据字体大小等工厂获取
/// </summary>
public class Editor2
{
    private List<Character2> chars = new List<Character2>();

    public void AddCharacter(char c, string font, int size, int colorRgb)
    {
        var style = CharacterStypeFactory.GetStyle(font, size, colorRgb);
        chars.Add(new Character2(c, style));
    }
}

#endregion